//
//  MTOpenRedpackDetailViewController.swift
//  MT
//
//  Created by ooops on 2019/12/23.
//  Copyright © 2019 张强. All rights reserved.
//

import UIKit
import MTCategory

class MTOpenRedpackHistoryViewController: BaseViewController {
    
//    private var openRedpackModel: MTOpenRedpackModel?
//
//    override init() {
//        super.init()
//    }
//
//    convenience init(_ openRedpackModel: MTOpenRedpackModel) {
//        self.init()
//        self.openRedpackModel = openRedpackModel
//        self.headerView.openRedpackModel = openRedpackModel
//    }
//
//    required public init?(coder aDecoder: NSCoder) {
//        fatalError("init(coder:) has not been implemented")
//    }
//
//    required public init(rounterParams params: Dictionary<String, Any>?) {
//        fatalError("init(rounterParams:) has not been implemented")
//    }
    
    private var result: [MTQueryResultModel] = []
    private var currentPage: Int = 1
    private let pageSize: Int = 20
    private var loadType: Int = 1
    private var popMenu: SwiftPopMenu!

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightMenuBtn)
        navigationItem.leftBarButtonItem = UIBarButtonItem(customView: closeBtn)
        view.addSubview(tableView)
        //presentPopupView(selectView)
        
        tableView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
        loadFirst()
    }
    
    
    // MARK: - 查询红包收入 / 支出记录
    private func query(loadMore: Bool) {
        let queryParam: [String : Any] = ["curPage" : currentPage, "pageSize" : pageSize, "type" : loadType]
        MTRedpackTool.default.queryRedpack(queryParam: queryParam, self) { [weak self] (model, isSuccess) in
            guard let weakSelf = self else { return }
            weakSelf.tableView.mj_footer?.endRefreshing()
            weakSelf.tableView.mj_header?.endRefreshing()
            if let m = model {
                m.isSender = weakSelf.loadType == 2
                debugPrint("message: ", m.message ?? "")
                if m.code != 200 {
                    weakSelf.tableView.mj_footer?.endRefreshingWithNoMoreData()
                }
                if let r = m.result {
                    if loadMore == true {
                        weakSelf.result = weakSelf.result + r
                        if (m.page?.pages == m.page?.curPage) {
                            weakSelf.tableView.mj_footer?.endRefreshingWithNoMoreData()
                        } else {
                            
                        }
                    } else {
                        weakSelf.result = r
                    }
                }
                
                weakSelf.headerView.openRedpackModel = model
                DispatchQueue.main.async {
                    weakSelf.tableView.reloadData()
                }
            }
        }
    }
    
    lazy var closeBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setTitle("关闭", for: .normal)
        btn.addTarget(self, action: #selector(dismissViewController), for: .touchUpInside)
        btn.setTitleColor(UIColor.text.x1d1a1a, for: .normal)
        btn.titleLabel?.font = PingFangSCMediumFont(16)
        return btn
    }()
    
    lazy var rightMenuBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setTitle("...", for: .normal)
        btn.addTarget(self, action: #selector(rightMenu), for: .touchUpInside)
        btn.setTitleColor(UIColor.text.x1d1a1a, for: .normal)
        return btn
    }()
    
    lazy var tableView: UITableView = {
        let table = UITableView(frame: .zero, style: .plain)
        table.delegate = self
        table.dataSource = self
        table.register(MTOpenRedpackHistoryCell.self, forCellReuseIdentifier: MTOpenRedpackHistoryCell.reuseIdentity())
        table.separatorStyle = .none
        table.tableFooterView = UIView()
        table.tableHeaderView = headerView
        table.mj_footer = ViewFactory.normalFooter(target: self, selector: #selector(loadMore))
        table.mj_header = ViewFactory.normalHeader(target: self, selector: #selector(loadFirst))
        //table.mj_footer?.ignoredScrollViewContentInsetBottom = 20
        table.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 20, right: 0)
        table.emptySetView = ViewFactory.emptySetView { [weak self] in

            guard let weakSelf = self else { return }

            weakSelf.loadFirst()

        }
        return table
    }()
    
    lazy var headerView: MTOpenRedpackHistoryHeaderView = {
        let v = MTOpenRedpackHistoryHeaderView(frame: CGRect(x: 0, y: 0, width: ScreenWidth, height: 167))
        v.backgroundColor = UIColor.theme.background
        return v
    }()
    
    
    @objc private func loadFirst() {
        self.currentPage = 1
        
        query(loadMore: false)
    }
    
    @objc private func loadMore() {
        
        self.currentPage = self.currentPage + 1
        
        query(loadMore: true)
        
    }
    
    @objc private func rightMenu() {
        
        //presentPopupView(selectView)
        //数据源（icon可不填）
        let popData = [(icon:"",title:"我收到的"),
                       (icon:"",title:"我发出的")]
        
        //设置参数
        let parameters:[SwiftPopMenuConfigure] = [
            .PopMenuTextColor(UIColor.black),
            .popMenuItemHeight(44),
            .PopMenuTextFont(PingFangSCRegularFont(15)),
            .popMenuAlpha(0),
            .popMenuMargin(16),
            .PopMenuBackgroudColor(UIColor.text.x999999)
        ]
        
        
        //init  (test随机生成点位置，注意：arrow点是基于屏幕的位置)
        popMenu = SwiftPopMenu(menuWidth: 100, arrow: CGPoint(x: ScreenWidth - 20, y: NavigationBarHeight + StatusBarHeight - 10), datas: popData,configures: parameters)

        //click
        popMenu.didSelectMenuBlock = { [weak self] (index:Int) -> Void in
            guard let weakSelf = self else { return }
            if index == 0 {
                if weakSelf.loadType == 1 {
                    return
                }
                weakSelf.loadType = 1
                weakSelf.query(loadMore: false)
            } else {
                if weakSelf.loadType == 2 {
                    return
                }
                weakSelf.loadType = 2
                weakSelf.query(loadMore: false)
            }
            self?.popMenu = nil
        }
        //show
        popMenu.show()
        
    }
    
    @objc private func dismissViewController() {
        self.dismiss(animated: true, completion: nil)
    }

}

extension MTOpenRedpackHistoryViewController: UITableViewDelegate, UITableViewDataSource {
    
    //MARK: UITableViewDataSource
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.result.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: MTOpenRedpackHistoryCell.reuseIdentity(), for: indexPath) as! MTOpenRedpackHistoryCell
        configureCell(cell: cell, forRowAt: indexPath)
        return cell
    }
    
    func configureCell(cell: MTOpenRedpackHistoryCell, forRowAt indexPath: IndexPath) {
        let model = self.result[indexPath.row]
        cell.model = model
    }
    
    //MARK: UITableViewDelegate
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 76
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return CGFloat.leastNonzeroMagnitude
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return CGFloat.leastNonzeroMagnitude
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return nil
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return nil
    }
    
}
